<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useRouter, useRoute } from 'vue-router'
import { initApi, infoApi, saveApi, exportOrderExcelApi } from '@/api/financial'
import { merchantDetailsApi } from '@/api/BusinessManagement'
import {
  ElButton,
  ElInput,
  ElInputNumber,
  ElForm,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElMessage
} from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { formatTime } from '@/utils'
import Detail from './components/Detail.vue'
import { computed, ref } from 'vue'

const { t } = useI18n()
const { go } = useRouter()
const { query } = useRoute()
const id = query.id
const withdrawalUserId = query.withdrawalUserId
const checkBillId = Number(query.checkBillId)

const showDrawer = ref(false)
const total = ref()
const businessDetail = ref<any>({})
const loading = ref(false)
const pre = () => {
  showDrawer.value = true
}
const formRef = ref()
const inputForm = ref<any>({})

const init = (withdrawalId) => {
  if (checkBillId && checkBillId != 0) {
    infoApi({ checkBillId }).then((res) => {
      inputForm.value = res.data
    })
  } else {
    initApi({ withdrawalId }).then((res) => {
      inputForm.value = res.data
    })
  }
}
const getMerchantDetails = () => {
  merchantDetailsApi(withdrawalUserId).then((res) => {
    businessDetail.value = res.data
  })
}
const add = () => {
  inputForm.value.feeItems.push({ itemAmt: 0, itemDesc: '', type: 4 })
}
const del = (index) => {
  inputForm.value.feeItems.splice(index, 1)
}
const save = async () => {
  let valid = true
  inputForm.value.feeItems.forEach((item, index) => {
    if (!item.itemDesc) {
      valid = false
      ElMessage.error(`第${index}行的费用项目名称不能为空`)
      return
    }
    if (!item.itemAmt) {
      valid = false
      ElMessage.error(`第${index}行的费用项目金额不能为空`)
      return
    }
  })
  if (valid) {
    loading.value = true
    let formData = {
      checkBillId: checkBillId || inputForm.value.id,
      items: inputForm.value.feeItems
    }
    saveApi(formData)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success('保存成功')
          setTimeout(() => {
            go(-1)
          }, 1000)
        } else {
          ElMessage.error(res.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
}
total.value = computed(() => {
  return (
    inputForm.value.withdrawalAmt -
    inputForm.value?.feeItems?.reduce((acc, cur) => {
      return acc + cur.itemAmt
    }, 0)
  ).toFixed(2)
})
const download = async () => {
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const res = await exportOrderExcelApi({ withdrawalId: id })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `订单明细${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
init(id)
getMerchantDetails()
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentDetailWrap class="flex-[3] ml-20px" title="商户本金提现核算">
      <template #header>
        <ElButton @click="go(-1)">
          {{ t('common.back') }}
        </ElButton>
      </template>
      <div>
        <div class="font-bold py-2">商户信息</div>
        <div class="flex text-14px p-2">
          <div class="w-1/3">
            <span>商户ID：</span>
            <span>{{ businessDetail.id }}</span>
          </div>
          <div class="w-1/3">
            <span>商户名称：</span>
            <span>{{ businessDetail.merchantShortName }}</span>
          </div>
        </div>
        <div class="flex text-14px p-2">
          <div class="w-1/3">
            <span>账户名称：</span>
            <span>{{ businessDetail.appMerchantEnterApplyPageVo?.cardName }}</span>
          </div>
          <div class="w-1/3">
            <span>银行账号：</span>
            <span>{{ businessDetail.appMerchantEnterApplyPageVo?.cardNo }}</span>
          </div>
          <div class="w-1/3">
            <span>开户行：</span>
            <span>{{ businessDetail.appMerchantEnterApplyPageVo?.bankName }}</span>
          </div>
        </div>
        <div class="font-bold py-2">核算信息</div>
        <div v-if="inputForm.checkType === 1" class="flex text-14px p-2">
          <div class="flex w-1/2 justify-end">
            <ElButton type="success" @click="download">下载订单明细</ElButton>
          </div>
        </div>
        <div v-if="inputForm.checkType === 1" class="flex text-14px p-2">
          <div class="w-1/2">
            <span>结算金额：</span>
            <span>￥{{ inputForm.finalAmt }}</span>
          </div>
        </div>
        <div v-if="inputForm.checkType === 2" class="flex text-14px p-2">
          <div class="w-1/2">
            <ElTable :data="inputForm.billItems">
              <ElTableColumn label="账单日期" prop="itemDesc" />
              <ElTableColumn label="结算金额">
                <template #default="{ row }">
                  <span>￥{{ row.itemAmt }}</span>
                </template>
              </ElTableColumn>
            </ElTable>
          </div>
        </div>
        <div class="flex text-14px p-2">
          <div class="w-1/2">
            <ElForm :model="inputForm" ref="formRef">
              <ElTable :data="inputForm.feeItems">
                <ElTableColumn label="扣费项目名称">
                  <template #default="{ row, $index }">
                    <ElFormItem
                      label-width="0"
                      :prop="'inputForm.feeItems[' + $index + '][itemDesc]'"
                      :rules="[{ required: false, message: '必填项不能为空', trigger: 'blur' }]"
                    >
                      <ElInput :disabled="row.type === 3" v-model="row.itemDesc" />
                    </ElFormItem>
                  </template>
                </ElTableColumn>
                <ElTableColumn label="项目金额">
                  <template #default="{ row, $index }">
                    <ElFormItem
                      label-width="0"
                      :prop="'inputForm.feeItems[' + $index + '][itemAmt]'"
                      :rules="[{ required: false, message: '必填项不能为空', trigger: 'blur' }]"
                    >
                      -￥<ElInputNumber
                        :precision="2"
                        :controls="false"
                        :disabled="row.type === 3"
                        v-model="row.itemAmt"
                      />
                    </ElFormItem>
                  </template>
                </ElTableColumn>
                <ElTableColumn label="操作">
                  <template #default="{ row, $index }">
                    <ElButton v-if="row.type !== 3" type="primary" link @click="del($index)">
                      删除
                    </ElButton>
                  </template>
                </ElTableColumn>
              </ElTable>
            </ElForm>
          </div>
        </div>
        <div class="flex text-14px p-2">
          <div class="w-1/2">
            <ElButton type="primary" text @click="add">+添加费用项目</ElButton>
          </div>
        </div>
        <div class="flex text-14px p-2">
          <div class="w-1/2 flex justify-end items-center">
            <span class="mr-5 text-xl">
              合计：￥<span class="text-red-500">{{ total }}</span>
            </span>
            <ElButton v-if="checkBillId" type="primary" @click="pre">预览结算单</ElButton>
          </div>
        </div>
        <div class="flex text-14px p-2">
          <div class="w-1/2">
            <ElButton @click="go(-1)">取消</ElButton>
            <ElButton type="primary" :loading="loading" @click="save">保存</ElButton>
          </div>
        </div>
      </div>
    </ContentDetailWrap>
    <ElDrawer
      title="结算单预览"
      v-model="showDrawer"
      direction="rtl"
      size="800px"
      @close="showDrawer = false"
    >
      <Detail
        v-if="showDrawer"
        :feeItems="inputForm.feeItems"
        :billItems="inputForm.billItems"
        :id="checkBillId"
      />
    </ElDrawer>
  </div>
</template>
